#include "viml/debugger.h"
#include "viml/vm.h"
#include "viml/instruction.h"
#include <iostream>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <memory>

namespace viml {

Debugger::Debugger(std::shared_ptr<VM> virtual_machine)
    : vm(virtual_machine),
      state(DebuggerState::INACTIVE),
      step_mode_enabled(false),
      step_over_enabled(false),
      step_into_enabled(false),
      step_out_enabled(false),
      step_start_pc(0),
      step_start_stack_depth(0),
      current_pc(0),
      auto_load_source(true),
      show_instruction_disassembly(false),
      show_variable_values_on_stop(true),
      break_on_exception(true),
      trace_mode(false) {

    debug_info = std::make_shared<DebugInfo>();
    initialize_debugger();
}

// 虚拟机管理
void Debugger::set_vm(std::shared_ptr<VM> virtual_machine) {
    if (vm) {
        detach_from_vm();
    }

    vm = virtual_machine;
    if (vm) {
        attach_to_vm();
    }
}

void Debugger::attach_to_vm() {
    if (!vm) return;

    setup_vm_callbacks();
    vm->set_debugger(shared_from_this());
    set_state(DebuggerState::ACTIVE);
}

void Debugger::detach_from_vm() {
    if (!vm) return;

    cleanup_vm_callbacks();
    vm->set_debugger(nullptr);
    set_state(DebuggerState::INACTIVE);
}

// 调试信息管理
void Debugger::set_debug_info(std::shared_ptr<DebugInfo> info) {
    debug_info = info;
    if (auto_load_source && debug_info) {
        debug_info->load_source_file();
    }
}

bool Debugger::load_debug_info(const std::string& filename) {
    if (!debug_info) {
        debug_info = std::make_shared<DebugInfo>();
    }

    debug_info->set_source_file(filename);
    return debug_info->load_source_file();
}

// 启动和停止
bool Debugger::start() {
    if (!vm || !debug_info) {
        errors.emplace_back("调试器启动失败：虚拟机或调试信息未设置");
        return false;
    }

    initialize_debugger();
    set_state(DebuggerState::ACTIVE);

    DebugEventInfo info(DebugEvent::VM_PAUSED);
    info.message = "调试器已启动";
    trigger_event(info);

    return true;
}

void Debugger::stop() {
    if (state == DebuggerState::INACTIVE) {
        return;
    }

    cleanup_debugger();
    set_state(DebuggerState::INACTIVE);

    DebugEventInfo info(DebugEvent::VM_HALTED);
    info.message = "调试器已停止";
    trigger_event(info);
}

void Debugger::pause() {
    if (state == DebuggerState::RUNNING) {
        transition_to_paused();

        DebugEventInfo info(DebugEvent::VM_PAUSED, current_pc, get_current_line());
        info.message = "执行已暂停";
        trigger_event(info);
    }
}

void Debugger::resume() {
    if (state == DebuggerState::PAUSED) {
        transition_to_running();

        DebugEventInfo info(DebugEvent::LINE_CHANGE, current_pc, get_current_line());
        info.message = "执行已恢复";
        trigger_event(info);
    }
}

void Debugger::reset() {
    stop();
    step_mode_enabled = false;
    step_over_enabled = false;
    step_into_enabled = false;
    step_out_enabled = false;
    step_start_pc = 0;
    step_start_stack_depth = 0;
    step_function_name.clear();

    current_call_stack.clear();
    current_variables.clear();
    current_pc = 0;
    current_function.clear();

    variable_watchers.clear();
    event_callbacks.clear();
    errors.clear();
    reset_statistics();
}

// 断点管理
size_t Debugger::set_breakpoint(int line, const std::string& condition) {
    if (!debug_info) {
        errors.emplace_back("设置断点失败：调试信息未初始化");
        return 0;
    }

    size_t bp_id = debug_info->add_breakpoint(line, condition);

    DebugEventInfo info(DebugEvent::LINE_CHANGE);
    info.message = "设置断点 " + std::to_string(bp_id) + " 在第 " + std::to_string(line) + " 行";
    trigger_event(info);

    return bp_id;
}

size_t Debugger::set_breakpoint(const std::string& file, int line, const std::string& condition) {
    if (!debug_info) {
        errors.emplace_back("设置断点失败：调试信息未初始化");
        return 0;
    }

    SourceLocation location(file, line);
    size_t bp_id = debug_info->add_breakpoint(location, condition);

    DebugEventInfo info(DebugEvent::LINE_CHANGE);
    info.message = "设置断点 " + std::to_string(bp_id) + " 在 " + location.to_string();
    trigger_event(info);

    return bp_id;
}

size_t Debugger::set_breakpoint(size_t pc, const std::string& condition) {
    if (!debug_info) {
        errors.emplace_back("设置断点失败：调试信息未初始化");
        return 0;
    }

    size_t bp_id = debug_info->add_breakpoint(pc, condition);

    DebugEventInfo info(DebugEvent::LINE_CHANGE);
    info.message = "设置断点 " + std::to_string(bp_id) + " 在 PC=" + std::to_string(pc);
    trigger_event(info);

    return bp_id;
}

bool Debugger::remove_breakpoint(size_t breakpoint_id) {
    if (!debug_info) {
        return false;
    }

    bool result = debug_info->remove_breakpoint(breakpoint_id);
    if (result) {
        DebugEventInfo info(DebugEvent::LINE_CHANGE);
        info.message = "移除断点 " + std::to_string(breakpoint_id);
        trigger_event(info);
    }

    return result;
}

bool Debugger::remove_breakpoint(int line) {
    if (!debug_info) {
        return false;
    }

    const BreakpointInfo* bp = debug_info->get_breakpoint_at_line(line);
    if (bp) {
        return remove_breakpoint(bp->id);
    }

    return false;
}

bool Debugger::remove_breakpoint(const std::string& file, int line) {
    (void)file; // 避免未使用参数警告
    if (!debug_info) {
        return false;
    }

    return remove_breakpoint(line); // 简化实现，忽略文件路径
}

bool Debugger::enable_breakpoint(size_t breakpoint_id, bool enabled) {
    if (!debug_info) {
        return false;
    }

    return debug_info->enable_breakpoint(breakpoint_id, enabled);
}

bool Debugger::disable_breakpoint(size_t breakpoint_id) {
    return enable_breakpoint(breakpoint_id, false);
}

void Debugger::clear_all_breakpoints() {
    if (debug_info) {
        debug_info->clear_all_breakpoints();
    }
}

std::vector<const BreakpointInfo*> Debugger::get_all_breakpoints() const {
    if (debug_info) {
        return debug_info->get_all_breakpoints();
    }
    return {};
}

std::vector<const BreakpointInfo*> Debugger::get_enabled_breakpoints() const {
    if (debug_info) {
        return debug_info->get_enabled_breakpoints();
    }
    return {};
}

const BreakpointInfo* Debugger::get_breakpoint(size_t breakpoint_id) const {
    if (debug_info) {
        return debug_info->get_breakpoint(breakpoint_id);
    }
    return nullptr;
}

bool Debugger::has_breakpoint_at(int line) const {
    return debug_info && debug_info->has_breakpoint_at_line(line);
}

bool Debugger::has_breakpoint_at(const std::string& file, int line) const {
    (void)file; // 避免未使用参数警告
    return has_breakpoint_at(line); // 简化实现
}

// 单步调试
void Debugger::step_into() {
    step_mode_enabled = true;
    step_into_enabled = true;
    step_over_enabled = false;
    step_out_enabled = false;
    step_start_pc = current_pc;
    step_start_stack_depth = current_call_stack.size();
    step_function_name = current_function;

    transition_to_step_mode();
}

void Debugger::step_over() {
    step_mode_enabled = true;
    step_into_enabled = false;
    step_over_enabled = true;
    step_out_enabled = false;
    step_start_pc = current_pc;
    step_start_stack_depth = current_call_stack.size();
    step_function_name = current_function;

    transition_to_step_mode();
}

void Debugger::step_out() {
    step_mode_enabled = true;
    step_into_enabled = false;
    step_over_enabled = false;
    step_out_enabled = true;
    step_start_pc = current_pc;
    step_start_stack_depth = current_call_stack.size();
    step_function_name = current_function;

    transition_to_step_mode();
}

void Debugger::step_next() {
    step_mode_enabled = true;
    step_into_enabled = true;
    step_over_enabled = false;
    step_out_enabled = false;
    step_start_pc = current_pc;
    step_start_stack_depth = current_call_stack.size();

    transition_to_step_mode();
}

void Debugger::continue_execution() {
    step_mode_enabled = false;
    step_into_enabled = false;
    step_over_enabled = false;
    step_out_enabled = false;

    transition_to_running();
}

// 调试器控制接口实现
bool Debugger::should_pause() const {
    // 如果在单步模式，检查是否应该暂停
    if (step_mode_enabled) {
        return true;  // 单步模式下每条指令都暂停
    }

    // 如果调试器处于暂停状态，返回true
    return state == DebuggerState::PAUSED;
}

bool Debugger::check_breakpoint(size_t pc, int line) {
    // 检查是否有断点在指定位置
    if (!debug_info) return false;

    auto breakpoints = debug_info->get_all_breakpoints();
    for (const auto* bp : breakpoints) {
        if (bp->enabled && bp->location.line == line) {
            // 更新当前PC和行号
            current_pc = pc;

            // 更新统计信息
            stats.breakpoints_hit++;
            stats.events_fired++;

            // 更新当前上下文
            update_current_context();

            // 触发断点命中事件
            DebugEventInfo info(DebugEvent::BREAKPOINT_HIT, pc, line, current_function);
            info.message = "断点命中";
            trigger_event(info);

            set_state(DebuggerState::PAUSED);
            return true;
        }
    }
    return false;
}

void Debugger::on_vm_paused(size_t pc, int line) {
    current_pc = pc;

    // 更新当前上下文
    update_current_context();

    // 触发暂停事件
    DebugEventInfo info(DebugEvent::VM_PAUSED, pc, line, current_function);
    info.message = "虚拟机暂停执行";
    trigger_event(info);

    set_state(DebuggerState::PAUSED);
}

void Debugger::on_breakpoint_hit(size_t pc, int line) {
    current_pc = pc;

    // 更新统计信息
    stats.breakpoints_hit++;
    stats.events_fired++;

    // 更新当前上下文
    update_current_context();

    // 触发断点命中事件
    DebugEventInfo info(DebugEvent::BREAKPOINT_HIT, pc, line, current_function);
    info.message = "断点命中";
    trigger_event(info);

    set_state(DebuggerState::PAUSED);
}


void Debugger::run_to_line(int line) {
    if (!debug_info) {
        errors.emplace_back("运行到指定行失败：调试信息未设置");
        return;
    }

    size_t target_pc = debug_info->pc_for_line(line);
    if (target_pc == static_cast<size_t>(-1)) {
        errors.emplace_back("运行到指定行失败：行号 " + std::to_string(line) + " 不可执行");
        return;
    }

    // 设置临时断点并继续执行
    size_t temp_bp = set_breakpoint(line);
    (void)temp_bp; // 避免未使用变量警告，后续会用于移除断点
    continue_execution();

    // 注意：这里需要实现断点命中后自动移除临时断点的逻辑
}

void Debugger::run_to_function(const std::string& function_name) {
    if (!debug_info) {
        errors.emplace_back("运行到指定函数失败：调试信息未设置");
        return;
    }

    const FunctionInfo* func = debug_info->get_function(function_name);
    if (!func) {
        errors.emplace_back("运行到指定函数失败：函数 " + function_name + " 未找到");
        return;
    }

    size_t temp_bp = set_breakpoint(func->location.line);
    (void)temp_bp; // 避免未使用变量警告，后续会用于移除断点
    continue_execution();
}

// 执行控制
void Debugger::execute_instruction(size_t pc) {
    current_pc = pc;
    update_current_context();

    // 检查断点
    check_breakpoints();

    // 检查监视点
    check_watchpoints();

    // 处理单步调试
    if (is_in_step_mode() && !should_step_continue()) {
        handle_step_completion();
    }
}

void Debugger::handle_vm_state_change() {
    if (!vm) return;

    VMState vm_state = vm->get_state();

    switch (vm_state) {
        case VMState::RUNNING:
            if (state == DebuggerState::PAUSED || state == DebuggerState::ACTIVE) {
                transition_to_running();
            }
            break;

        case VMState::PAUSED:
            if (state == DebuggerState::RUNNING) {
                transition_to_paused();
            }
            break;

        case VMState::HALTED:
        case VMState::ERROR: {
            transition_to_paused();

            DebugEventInfo info(vm_state == VMState::ERROR ? DebugEvent::EXCEPTION_THROWN : DebugEvent::VM_HALTED);
            info.pc = current_pc;
            info.line = get_current_line();
            info.function = current_function;
            trigger_event(info);
            break;
        }

        default:
            break;
    }
}

void Debugger::process_debug_event(const DebugEventInfo& event) {
    // 更新内部状态
    switch (event.event) {
        case DebugEvent::BREAKPOINT_HIT:
            stats.breakpoints_hit++;
            break;

        case DebugEvent::STEP_COMPLETE:
            stats.steps_taken++;
            break;

        default:
            break;
    }

    stats.events_fired++;

    // 触发回调
    trigger_event(event);

    // 输出调试信息（如果启用）
    if (trace_mode) {
        std::cout << "[调试事件] " << event.message << std::endl;
    }
}

// 变量监视
size_t Debugger::add_variable_watcher(const std::string& variable_name, DebugCallback callback) {
    auto watcher = std::make_unique<VariableWatcher>(variable_name, callback);
    size_t watcher_id = generate_unique_watcher_id();

    // 这里简化实现，实际应该使用ID映射
    variable_watchers.push_back(std::move(watcher));
    stats.variables_watched = variable_watchers.size();

    return watcher_id;
}

bool Debugger::remove_variable_watcher(size_t watcher_id) {
    (void)watcher_id; // 避免未使用参数警告，简化实现
    // 简化实现，实际应该根据ID移除
    if (!variable_watchers.empty()) {
        variable_watchers.pop_back();
        stats.variables_watched = variable_watchers.size();
        return true;
    }
    return false;
}

void Debugger::clear_variable_watchers() {
    variable_watchers.clear();
    stats.variables_watched = 0;
}

void Debugger::update_variable_values() {
    if (!vm || !debug_info) return;

    // 从虚拟机获取当前变量值
    current_variables.clear();

    // 获取局部变量
    const auto& func = debug_info->get_function_at_pc(current_pc);
    if (func) {
        auto local_vars = debug_info->get_local_variables(func->name);
        for (const auto* var : local_vars) {
            // 这里应该从VM的寄存器或作用域管理器获取实际值
            // 简化实现
            current_variables[var->name] = Value();
        }
    }

    // 更新监视器
    for (auto& watcher : variable_watchers) {
        auto it = current_variables.find(watcher->get_variable_name());
        if (it != current_variables.end()) {
            watcher->update(it->second);
        }
    }
}

Value Debugger::get_variable_value(const std::string& name) const {
    auto it = current_variables.find(name);
    return (it != current_variables.end()) ? it->second : Value();
}

std::unordered_map<std::string, Value> Debugger::get_all_variables() const {
    return current_variables;
}

std::vector<std::string> Debugger::get_variable_names() const {
    std::vector<std::string> names;
    for (const auto& pair : current_variables) {
        names.push_back(pair.first);
    }
    return names;
}

// 调用栈管理
std::vector<std::string> Debugger::get_call_stack() const {
    return current_call_stack;
}

size_t Debugger::get_stack_depth() const {
    return current_call_stack.size();
}

int Debugger::get_current_line() const {
    if (debug_info) {
        return debug_info->line_for_pc(current_pc);
    }
    return -1;
}

// 源码信息
std::string Debugger::get_source_file() const {
    return debug_info ? debug_info->get_source_file() : "";
}

std::string Debugger::get_source_line(int line) const {
    return debug_info ? debug_info->get_source_line(line) : "";
}

int Debugger::get_line_count() const {
    return debug_info ? debug_info->get_line_count() : 0;
}

std::vector<int> Debugger::get_executable_lines() const {
    return debug_info ? debug_info->get_executable_lines() : std::vector<int>();
}

bool Debugger::is_executable_line(int line) const {
    return debug_info && debug_info->is_executable_line(line);
}

std::string Debugger::get_current_source_line() const {
    int line = get_current_line();
    return (line > 0) ? get_source_line(line) : "";
}

// 事件处理
void Debugger::add_event_callback(DebugCallback callback) {
    event_callbacks.push_back(callback);
}

void Debugger::remove_event_callback(const DebugCallback& callback) {
    (void)callback; // 避免未使用参数警告，简化实现
    // 简化实现，实际应该比较函数对象
    event_callbacks.clear();
}

void Debugger::clear_event_callbacks() {
    event_callbacks.clear();
}

void Debugger::trigger_event(const DebugEventInfo& event) {
    for (auto& callback : event_callbacks) {
        if (callback) {
            callback(event);
        }
    }
}

// 调试输出和格式化
std::string Debugger::format_current_location() const {
    std::ostringstream oss;

    if (debug_info) {
        SourceLocation location = debug_info->get_location(current_pc);
        oss << debug_info->format_location(location);
    } else {
        oss << "PC=" << current_pc;
    }

    if (!current_function.empty()) {
        oss << " in " << current_function << "()";
    }

    return oss.str();
}

std::string Debugger::format_call_stack() const {
    std::ostringstream oss;
    oss << "调用栈:\n";

    for (size_t i = 0; i < current_call_stack.size(); ++i) {
        oss << "  #" << i << ": " << current_call_stack[i];
        if (i == 0) {
            oss << " (当前)";
        }
        oss << "\n";
    }

    return oss.str();
}

std::string Debugger::format_variables() const {
    std::ostringstream oss;
    oss << "变量:\n";

    for (const auto& pair : current_variables) {
        oss << "  " << format_variable_info(pair.first, pair.second) << "\n";
    }

    return oss.str();
}

std::string Debugger::format_breakpoints() const {
    if (!debug_info) {
        return "断点信息不可用\n";
    }

    std::ostringstream oss;
    auto breakpoints = debug_info->get_all_breakpoints();

    if (breakpoints.empty()) {
        oss << "无断点\n";
    } else {
        oss << "断点列表:\n";
        for (const auto* bp : breakpoints) {
            oss << "  " << debug_info->format_breakpoint(*bp) << "\n";
        }
    }

    return oss.str();
}

std::string Debugger::format_current_state() const {
    std::ostringstream oss;

    oss << "调试器状态: ";
    switch (state) {
        case DebuggerState::INACTIVE: oss << "未激活"; break;
        case DebuggerState::ACTIVE: oss << "激活"; break;
        case DebuggerState::RUNNING: oss << "运行中"; break;
        case DebuggerState::PAUSED: oss << "已暂停"; break;
        case DebuggerState::STEP_MODE: oss << "单步模式"; break;
        case DebuggerState::STEPPING_OVER: oss << "单步跳过"; break;
        case DebuggerState::STEPPING_IN: oss << "单步进入"; break;
        case DebuggerState::STEPPING_OUT: oss << "单步跳出"; break;
    }

    oss << "\n当前位置: " << format_current_location() << "\n";

    if (!current_call_stack.empty()) {
        oss << format_call_stack();
    }

    if (!current_variables.empty()) {
        oss << format_variables();
    }

    return oss.str();
}

// 统计信息
Debugger::DebuggerStatistics Debugger::get_statistics() const {
    return stats;
}

void Debugger::reset_statistics() {
    stats = DebuggerStatistics();
}

// 错误处理
std::vector<Debugger::DebuggerError> Debugger::get_errors() const {
    return errors;
}

void Debugger::clear_errors() {
    errors.clear();
}

// 私有辅助方法
void Debugger::initialize_debugger() {
    if (debug_info && auto_load_source) {
        debug_info->load_source_file();
    }

    if (vm) {
        setup_vm_callbacks();
    }
}

void Debugger::cleanup_debugger() {
    if (vm) {
        cleanup_vm_callbacks();
    }

    variable_watchers.clear();
    event_callbacks.clear();
}

void Debugger::update_current_context() {
    if (!vm || !debug_info) return;

    // 更新当前PC对应的行号和函数信息
    (void)debug_info->line_for_pc(current_pc); // 调用以获取行号（可选）
    current_function = debug_info->extract_function_context(current_pc);

    // 更新调用栈（从虚拟机获取）
    if (vm->get_call_stack().size() > 0) {
        current_call_stack.clear();
        for (const auto& frame : vm->get_call_stack()) {
            if (!frame.function_name.empty()) {
                current_call_stack.push_back(frame.function_name);
            }
        }
    }

    // 更新变量值
    update_variable_values();
}

void Debugger::check_breakpoints() {
    if (!debug_info) return;

    const BreakpointInfo* bp = debug_info->get_breakpoint_at_pc(current_pc);
    if (bp && bp->enabled) {
        if (debug_info->should_break(current_pc, current_variables)) {
            on_breakpoint_hit(bp);
        }
    }
}

void Debugger::check_watchpoints() {
    // 变量监视器的检查已经在 update_variable_values 中完成
}

bool Debugger::should_step_continue() const {
    if (!step_mode_enabled) {
        return true;
    }

    size_t current_depth = current_call_stack.size();

    if (step_into_enabled) {
        return false; // step_into 总是在每条指令后停止
    }

    if (step_over_enabled) {
        // step_over: 同一层级停止，进入深层时继续
        return current_depth != step_start_stack_depth;
    }

    if (step_out_enabled) {
        // step_out: 回到上一层时停止
        return current_depth >= step_start_stack_depth;
    }

    return false;
}

void Debugger::handle_step_completion() {
    on_step_complete();
}

void Debugger::on_breakpoint_hit(const BreakpointInfo* bp) {
    if (!bp) return;

    debug_info->hit_breakpoint(bp->id);

    // 更新统计信息
    stats.breakpoints_hit++;
    stats.events_fired++;

    transition_to_paused();

    DebugEventInfo info(DebugEvent::BREAKPOINT_HIT, current_pc, get_current_line());
    info.function = current_function;
    info.message = "命中断点 " + std::to_string(bp->id);
    trigger_event(info);
}

void Debugger::on_step_complete() {
    transition_to_paused();

    DebugEventInfo info(DebugEvent::STEP_COMPLETE, current_pc, get_current_line());
    info.function = current_function;
    info.message = "单步执行完成";
    trigger_event(info);
}

void Debugger::on_function_entry(const std::string& function_name) {
    DebugEventInfo info(DebugEvent::FUNCTION_ENTRY, current_pc, get_current_line());
    info.function = function_name;
    info.message = "进入函数: " + function_name;
    trigger_event(info);
}

void Debugger::on_function_exit(const std::string& function_name) {
    DebugEventInfo info(DebugEvent::FUNCTION_EXIT, current_pc, get_current_line());
    info.function = function_name;
    info.message = "退出函数: " + function_name;
    trigger_event(info);
}

void Debugger::on_exception_thrown(const std::string& error_message) {
    if (break_on_exception) {
        transition_to_paused();
    }

    DebugEventInfo info(DebugEvent::EXCEPTION_THROWN, current_pc, get_current_line());
    info.function = current_function;
    info.message = "异常: " + error_message;
    trigger_event(info);
}

void Debugger::on_line_changed(int line) {
    DebugEventInfo info(DebugEvent::LINE_CHANGE, current_pc, line);
    info.function = current_function;
    trigger_event(info);
}

// 状态转换
void Debugger::set_state(DebuggerState new_state) {
    if (state != new_state) {
        state = new_state;
    }
}

void Debugger::transition_to_running() {
    set_state(DebuggerState::RUNNING);
}

void Debugger::transition_to_paused() {
    set_state(DebuggerState::PAUSED);
}

void Debugger::transition_to_step_mode() {
    set_state(step_into_enabled ? DebuggerState::STEPPING_IN :
                 step_over_enabled ? DebuggerState::STEPPING_OVER :
                 step_out_enabled ? DebuggerState::STEPPING_OUT :
                 DebuggerState::STEP_MODE);
}

void Debugger::setup_vm_callbacks() {
    // 这里应该设置VM的调试回调
    // 实际实现需要与VM类协调
}

void Debugger::cleanup_vm_callbacks() {
    // 清理VM的调试回调
}

void Debugger::on_vm_instruction_execute(size_t pc) {
    current_pc = pc;
    execute_instruction(pc);
}

void Debugger::on_vm_function_call(const std::string& function_name) {
    on_function_entry(function_name);
}

void Debugger::on_vm_function_return(const std::string& function_name) {
    on_function_exit(function_name);
}

void Debugger::on_vm_exception(const std::string& error) {
    on_exception_thrown(error);
}

// 内部工具方法
std::string Debugger::format_value(const Value& value) const {
    return value.to_string();
}

std::string Debugger::format_variable_info(const std::string& name, const Value& value) const {
    std::ostringstream oss;
    oss << name << " = " << format_value(value);
    return oss.str();
}

size_t Debugger::generate_unique_watcher_id() {
    static size_t next_id = 1;
    return next_id++;
}

bool Debugger::is_in_same_function(size_t pc1, size_t pc2) const {
    if (!debug_info) return false;

    const FunctionInfo* func1 = debug_info->get_function_at_pc(pc1);
    const FunctionInfo* func2 = debug_info->get_function_at_pc(pc2);

    return func1 && func2 && func1->name == func2->name;
}

size_t Debugger::get_function_stack_depth(const std::string& function_name) const {
    size_t depth = 0;
    for (const auto& func : current_call_stack) {
        if (func == function_name) {
            depth++;
        }
    }
    return depth;
}

} // namespace viml